package com.truyentranh.modules.epicvn;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.truyentranh.R;
import com.truyentranh.controls.AdsViewControl;
import com.truyentranh.controls.IOnComicChanged;
import com.truyentranh.controls.IOnFinalPage;
import com.truyentranh.controls.ImagePagerAdapter;
import com.truyentranh.controls.OnSaveComic;
import com.truyentranh.controls.onSocialAction;
import com.truyentranh.data.HaiBLMetalData;
import com.truyentranh.main.AdsBussiness;
import com.truyentranh.main.ComicBussiness;
import com.truyentranh.modules.haivl.HaiVLActivity;
import com.truyentranh.network.APIRequestWorker;
import com.truyentranh.network.Request;
import com.truyentranh.network.RequestListener;
import com.truyentranh.requester.EpicVnRequester;
import com.truyentranh.utils.AppSettingParams;
import com.truyentranh.utils.FaceBookUtils;
import com.truyentranh.utils.Logger;
import com.truyentranh.utils.Utils;
import com.truyentranh.utils.sqllite.datasource.TopicHaiBlData;

public class EpicVnActivity extends Activity implements RequestListener, IOnFinalPage, onSocialAction, IOnComicChanged {

	private ImagePagerAdapter imageComicAdapter;
	
	@Override
	protected void onDestroy() {
		if(imageComicAdapter != null){
			imageComicAdapter.clearListener();
		}
		super.onDestroy();
	}
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);

		// Remove notification bar
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.epicvn_activity_layout);
		init();

		TextView textView = (TextView) findViewById(R.id.titleActivity);
		textView.setText("EPIC-Câu chuyện của tôi");

//		initActionBar();

		Button moreFunction = (Button) findViewById(R.id.btnMoreFunctions);
		if (moreFunction != null) {
			moreFunction.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {
					openOptionsMenu();
				}
			});
		}
		Button back = (Button) findViewById(R.id.btnBackAcvitity);
		if (back != null) {
			back.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {
					finish();
				}
			});
		}
	}
	
	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		int itemId = item != null ? item.getItemId() : -1;
		switch (itemId) {
		case 1:
			Logger.logMe("Save default");
			ComicBussiness.getInstance(EpicVnActivity.this).doSaveCommicToDefault(EpicVnActivity.this, imageComicAdapter.getCurrentData(), new OnSaveComic() {

				public void onError(int errorCode) {
					processError(errorCode);
				}

				public void onDone(HaiBLMetalData blMetalData, TopicHaiBlData haiBlData) {
					// TODO Auto-generated
					// method stub

				}

				public void onDoneWithNewTopic(HaiBLMetalData blMetalData, TopicHaiBlData haiBlData) {
					Logger.logMe("Sai flow, chuyen gi da xay ra duoi tang bussiness");
				}
			});
			break;
		case 2:
//			Logger.logMe("Save ");
//			ComicBussiness.getInstance(EpicVnActivity.this).doSaveCommic(EpicVnActivity.this, imageComicAdapter.getCurrentData(), new OnSaveComic() {
//
//				public void onError(int errorCode) {
//					processError(errorCode);
//				}
//
//				public void onDone(HaiBLMetalData blMetalData, TopicHaiBlData haiBlData) {
//					// TODO Auto-generated
//					// method stub
//
//				}
//
//				public void onDoneWithNewTopic(HaiBLMetalData blMetalData, TopicHaiBlData haiBlData) {
//					if (haiBlData != null) {						
//						showNotice("Thông báo", "�?ã dùng \"" + haiBlData.getName() + "\" làm chủ đ�? lưu mặc định.\nTip : Bạn có thể thay đổi"
//								+ " chủ đ�? mặc định này trong phần thiết lập của ứng dụng");
//					}
//				}
//			});
//			break;
			Utils.downloadPhoto(this, 0, this, imageComicAdapter.getCurrentData().getImageUrl(), getResources());
			break;
		case 3:
			Logger.logMe("facebook");
			FaceBookUtils.doShareFaceBook(imageComicAdapter.getCurrentData(), EpicVnActivity.this);
			break;
		case 4:
			doRefreshPage();
			Logger.logMe("refresh");
			break;
		case 5 :
			FaceBookUtils.doShareApplication(this);
			break;
		case 6 :
			doComment(imageComicAdapter.getCurrentData());
			break;
		case 7 :
			Utils.setWallpaper(this, 0, this,  imageComicAdapter.getCurrentData().getImageUrl(), getResources());
			break;
		}
		// TODO Auto-generated method stub
		return super.onMenuItemSelected(featureId, item);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		if (ComicBussiness.getInstance(this).getDefaultComicTopic() != null && ComicBussiness.getInstance(this).getDefaultComicTopic().getId() != -1) {
			menu.add(1, 1, 1, "Lưu " + ComicBussiness.getInstance(this).getDefaultComicTopic().getName()).setIcon(R.drawable.ic_save_default);
		}
		menu.add(1, 2, 2, "Lưu").setIcon(R.drawable.ic_saved);
		menu.add(3, 3, 3, "Facebook").setIcon(R.drawable.ic_facebook);
		menu.add(4, 4, 4, "Tải lại").setIcon(R.drawable.ic_refresh);
		menu.add(5, 5, 5, "Chia sẻ App").setIcon(R.drawable.ic_share);
		menu.add(5, 6, 6, "Bình luận").setIcon(R.drawable.ic_comment);
		menu.add(6, 7, 5, "�?ặt hình n�?n").setIcon(R.drawable.ic_wall);
		return super.onCreateOptionsMenu(menu);
	}
	
	void doAdsByServer() {
		AdsBussiness.getInstance().doGetAdsFromServer(this, prView);
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			finish();
			return true;
		}

		return super.onKeyDown(keyCode, event);
	}

	void processError(int errorCode) {
		String error = "";
		switch (errorCode) {
		
		case OnSaveComic.CREATE_TOPIC_ERROR:
			error = "Không thể tạo được chủ đ�?.";
			break;
		case OnSaveComic.DB_NOT_FOUND:
			error = "Không tìm thấy tập tin dữ liệu.";
			break;
		case OnSaveComic.DEFAULT_TOPIC_NOTFOUND:
			error = "Không tìm thấy chủ đ�? mặc định.";
			break;
		case OnSaveComic.IMAGE_NOT_FOUND:
			error = "Không có truyện hiển thị.";
			break;
		case OnSaveComic.INSERT_COMIC_ERROR:
			error = "Không thể thêm truyện vào máy.";
			break;
		case OnSaveComic.TOPIC_NAME_INVAILD:
			error = "Tên chủ đ�? không đúng.";
			break;
		case OnSaveComic.TOPIC_NOTFOUND:
			error = "Không tìm thấy chủ đ�?.";
			break;
		}
		if(!error.equals("")){
			Toast.makeText(EpicVnActivity.this, error, 1000).show();
		}
	}

	void showNotice(String title, String message) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(title);
		builder.setMessage(message);
		builder.setPositiveButton("�?óng", null);

		AlertDialog notice = builder.create();
		notice.show();
	}

	void doRefreshPage() {
		onStartUp();
	}

//	private QuickAction mQuickAction;
//
//	void initActionBar() {
//		mQuickAction = QuickAction.getCommonActionBar(EpicVnActivity.this, ComicBussiness.getInstance(this).getDefaultComicTopic(), new OnActionItemClickListener() {
//
//			public void onItemClick(int pos) {
//				if (ComicBussiness.getInstance(EpicVnActivity.this).getDefaultComicTopic() == null) {
//					if (pos == 0) {
//						ComicBussiness.getInstance(EpicVnActivity.this).doSaveCommic(EpicVnActivity.this, imageComicAdapter.getCurrentData(), new OnSaveComic() {
//
//							public void onError(int errorCode) {
//								processError(errorCode);
//							}
//
//							public void onDone(HaiBLMetalData blMetalData, TopicHaiBlData haiBlData) {
//								// TODO Auto-generated method stub
//
//							}
//
//							public void onDoneWithNewTopic(HaiBLMetalData blMetalData, TopicHaiBlData haiBlData) {
//								if (haiBlData != null) {
//									initActionBar();
//									showNotice("Thông báo", "�?ã dùng \"" + haiBlData.getName() + "\" làm chủ đ�? lưu mặc định.\nTip : Bạn có thể thay đổi" + " chủ đ�? mặc định này trong phần thiết lập của ứng dụng");
//								}
//							}
//						});
//					} else if (pos == 1) {
//						FaceBookUtils.doShareFaceBook(imageComicAdapter.getCurrentData(), EpicVnActivity.this);
//					} else if (pos == 2) {
//						doRefreshPage();
//					}  else if(pos == 3){
//						FaceBookUtils.makeFriend(imageComicAdapter.getCurrentData(),EpicVnActivity.this);
//					}
//				} else {
//					if (pos == 0) {
//						ComicBussiness.getInstance(EpicVnActivity.this).doSaveCommicToDefault(EpicVnActivity.this, imageComicAdapter.getCurrentData(), new OnSaveComic() {
//
//							public void onError(int errorCode) {
//								processError(errorCode);
//							}
//
//							public void onDone(HaiBLMetalData blMetalData, TopicHaiBlData haiBlData) {
//								// TODO Auto-generated method stub
//
//							}
//
//							public void onDoneWithNewTopic(HaiBLMetalData blMetalData, TopicHaiBlData haiBlData) {
//								Logger.logMe("Sai flow, chuyen gi da xay ra duoi tang bussiness");
//							}
//						});
//					} else if (pos == 1) {
//						ComicBussiness.getInstance(EpicVnActivity.this).doSaveCommic(EpicVnActivity.this, imageComicAdapter.getCurrentData(), new OnSaveComic() {
//
//							public void onError(int errorCode) {
//								processError(errorCode);
//							}
//
//							public void onDone(HaiBLMetalData blMetalData, TopicHaiBlData haiBlData) {
//								// TODO Auto-generated method stub
//
//							}
//
//							public void onDoneWithNewTopic(HaiBLMetalData blMetalData, TopicHaiBlData haiBlData) {
//								if (haiBlData != null) {
//									initActionBar();
//									showNotice("Thông báo", "�?ã dùng \"" + haiBlData.getName() + "\" làm chủ đ�? lưu mặc định.\nTip : Bạn có thể thay đổi" + " chủ đ�? mặc định này trong phần thiết lập của ứng dụng");
//								}
//							}
//						});
//					} else if (pos == 2) {
//						FaceBookUtils.doShareFaceBook(imageComicAdapter.getCurrentData(), EpicVnActivity.this);
//					} else if (pos == 3) {
//						doRefreshPage();
//					} else if(pos == 4){
//						FaceBookUtils.makeFriend(imageComicAdapter.getCurrentData(),EpicVnActivity.this);
//					}
//				}
//
//			}
//		});
//	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();

		onStartUp();
	}

	private int lastId = -1;
	long currentRequestId = -1;

	void init() {
	}

	void getComicFromServer(RequestListener listener) {
		EpicVnRequester requester = EpicVnRequester.getNew(lastId, listener);
		currentRequestId = AppSettingParams.nextRequestId();
		requester.setRequestId(currentRequestId);
		APIRequestWorker.getInstance().addAPIRequest(requester);
	}

	private void doComment(final HaiBLMetalData blMetalData) {
		if(blMetalData != null){
			Intent intent = new Intent(getApplication(), EpicCommentActivity.class);
			if (blMetalData != null) {
				intent.putExtra("IMAGE_ID", blMetalData.getDetailUrl());
			}
			startActivity(intent);
		}
//		facebook = new Facebook(GlobalData.FACEBOOK_APP_ID);
//		boolean isValid = SessionStore.restore(facebook, getApplicationContext());
//		if (isValid) {
//			Logger.logMe(">>>>>>>>>>Logged before");
//			Logger.logMe("getAccessToken " + facebook.getAccessToken());
//			Logger.logMe("getAccessExpires " + facebook.getAccessExpires());
//			Intent intent = new Intent(getApplication(), EpicCommentActivity.class);
//			if (blMetalData != null) {
//				intent.putExtra("IMAGE_ID", blMetalData.getDetailUrl());
//			}
//			startActivity(intent);
//		} else {
//			facebook.authorize(this, new DialogListener() {
//
//				public void onFacebookError(FacebookError e) {
//					// TODO Auto-generated method stub
//
//				}
//
//				public void onError(DialogError e) {
//					// TODO Auto-generated method stub
//
//				}
//
//				public void onComplete(Bundle values) {
//					if (facebook != null) {
//						// TODO Auto-generated method stub
//						Logger.logMe("getAccessToken " + facebook.getAccessToken());
//						Logger.logMe("getAccessExpires " + facebook.getAccessExpires());
//						SessionStore.save(facebook, getApplicationContext());
//						Intent intent = new Intent(getApplication(), EpicCommentActivity.class);
//						if (blMetalData != null) {
//							intent.putExtra("IMAGE_ID", blMetalData.getDetailUrl());
//						}
//						startActivity(intent);
//					} else {
//
//					}
//				}
//
//				public void onCancel() {
//					// TODO Auto-generated method stub
//
//				}
//			});
//		}
	}



	public void commicChanged(HaiBLMetalData blMetalData) {
		if(blMetalData != null){
			if(imageDescription != null){
				imageDescription.setText(blMetalData.getTitleDescription());
			}
			if (commentView != null) {
				String comment = getResources().getString(R.string.comment_string);
				if(!blMetalData.getCommentCount().equals(""))
					comment = blMetalData.getCommentCount() + " " + comment;
				commentView.setText(comment);
			}
		}
	}
	
	ViewPager viewPager = null;
	AdsViewControl prView =  null;
	LinearLayout loading = null;
	LinearLayout loadingError = null;
	TextView imageDescription =  null;
	LinearLayout menuBar = null;
	TextView commentView = null;
	LinearLayout loadingFinalPage = null;
	public void onStartUp() {
		viewPager = (ViewPager) findViewById(R.id.view_pager);
		prView = (AdsViewControl) findViewById(R.id.prview);
		loadingFinalPage   = (LinearLayout) findViewById(R.id.loadingFinalPage);
		loading = (LinearLayout) findViewById(R.id.loadingpage);
		loadingError = (LinearLayout) findViewById(R.id.loadingError);
		imageDescription = (TextView)findViewById(R.id.imageDescription);
		menuBar = (LinearLayout)findViewById(R.id.menubar);		
		commentView = (TextView)findViewById(R.id.commentView);
		
		Button btnShare = (Button) findViewById(R.id.btnShare);
		btnShare.setVisibility(View.GONE);
		commentView.setVisibility(View.GONE);
		
		loadingError.setVisibility(View.INVISIBLE);
		viewPager.setVisibility(View.INVISIBLE);
		prView.setVisibility(View.INVISIBLE);
		loading.setVisibility(View.VISIBLE);
		menuBar.setVisibility(View.INVISIBLE);
		
		commentView.setVisibility(View.GONE);		
//		commentView.setText(" Bình luận");
		
		if(imageComicAdapter == null){			
			imageComicAdapter = new ImagePagerAdapter(this);
			imageComicAdapter.setOnFinalPage(this);	
			imageComicAdapter.setComicChanged(this);
		}
		viewPager.setOnPageChangeListener(imageComicAdapter);
		imageComicAdapter.clearData();
		
		RequestListener listener =  new RequestListener() {
			
			public void onRequestFailed(String errorMsg, Request request) {
				runOnUiThread(new Runnable() {
					public void run() {					
						imageComicAdapter.clearData();
						loading.setVisibility(View.GONE);
						loadingError.setVisibility(View.VISIBLE);
						doAdsByServer();
					}
				});
			}
			
			public void onRequestComplete(Request request) {
				// TODO Auto-generated method stub
				if(request instanceof EpicVnRequester && currentRequestId == request.getRequestId()){
					ArrayList<HaiBLMetalData> datas = ((EpicVnRequester)request).getDataList();
					imageComicAdapter.setMetalData(datas);
					runOnUiThread(new Runnable() {
						public void run() {
							commentView.setVisibility(View.GONE);
							menuBar.setVisibility(View.VISIBLE);
							loading.setVisibility(View.GONE);
							prView.setVisibility(View.VISIBLE);
							viewPager.setVisibility(View.VISIBLE);
							viewPager.setAdapter(imageComicAdapter);
							imageComicAdapter.onPageSelected(0);
							viewPager.invalidate();
							doAdsByServer();
						}
					});						
				}
			}
		};			
		//khi doi tab can reset lai so page
		//cached lai nhu the nao
		getComicFromServer(listener);
	}

	public void onRequestComplete(Request request) {

	}

	public void onRequestFailed(String errorMsg, Request request) {
		// TODO Auto-generated method stub

	}

	public void onFinalPage() {

	}

	public void onComment(HaiBLMetalData data) {
		doComment(data);
	}

	public void onLike(HaiBLMetalData data) {
		// TODO Auto-generated method stub

	}

	int countAds = 0;
	public void onFinalItem(HaiBLMetalData data) {
		loadingFinalPage.setVisibility(View.VISIBLE);
		countAds++;
//		if(countAds >= 2){
			countAds = 0;
			doAdsByServer();
//		}
		RequestListener listener = new RequestListener() {

			public void onRequestFailed(String errorMsg, Request request) {
				// TODO Auto-generated method stub
				Logger.logMe(">>>>Fail");
				runOnUiThread(new Runnable() {
					public void run() {
						loadingFinalPage.setVisibility(View.GONE);
					}					
				});
			}

			public void onRequestComplete(Request request) {
				// TODO Auto-generated method stub
				if (request instanceof EpicVnRequester && currentRequestId == request.getRequestId()) {
					final ArrayList<HaiBLMetalData> datas = ((EpicVnRequester) request).getDataList();
					runOnUiThread(new Runnable() {
						public void run() {
							loadingFinalPage.setVisibility(View.GONE);
							if (imageComicAdapter != null) {
								imageComicAdapter.setMetalData(datas);
								imageComicAdapter.notifyDataSetChanged();
							}								
						}
					});
				}
			}
		};

		if (data != null) {
			String url = data.getDetailUrl();
			if (url != null && url.indexOf("/") != -1) {
				String[] rs = url.split("/");
				if (rs.length > 0) {
					String id = rs[rs.length - 1].trim();

					try {
						int mId = Integer.parseInt(id.trim());
						this.lastId = mId;
						getComicFromServer(listener);
					} catch (NumberFormatException e) {

					}
				}
			}
		}
	}
}
